package com.dmgis.qxfw.dataservice.businessservice.cdtt.controller;


import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.ContoursData;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.Equalline;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.potential_points;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.sl_warning;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.tour_stations;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.waterlogging_fcst;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.ActualData;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.cdtt.service.TowerSatelliteService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.dmgis.service.DmServiceConnector;
import com.dmgis.weblib.MapCommon;
import com.dmgis.weblib.MapProj;
import com.dmgis.weblib.MapProjPara;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("/Tower")
public class TowerSatelliteController {
    @Resource
    TowerSatelliteService towerSatelliteService;

    @Resource
    private  ITransformService transformService;

    MongoService1 ms = new MongoService1();

    DmServiceConnector conn = new DmServiceConnector("localhost", "6163");//改成181地址

    @RequestMapping("/initScale")
    @ResponseBody
    public Object initScalePage() {
        ArrayList<Object> resultList = new ArrayList<Object>();
        // 时间
        DateTime endTime = new DateTime(towerSatelliteService.getScaleNewDate());
        resultList.add(endTime.toDateTimeString());
        // 区县
        List<SmallScaleStation> countyList = towerSatelliteService.getCitySta();
        List<EasyuiTree> easyuiTrees = new ArrayList<>();
        for (int i = 0; i < countyList.size(); i++) {
            EasyuiTree tree = new EasyuiTree();
            tree.setId(i + 1);
            tree.setChecked(true);
            tree.setText(countyList.get(i).getCounty().trim());
            easyuiTrees.add(tree);
        }
        resultList.add(easyuiTrees);
        // 铁塔站点
        List<tower_station> stationList = towerSatelliteService.getTownStaList();
        Map<String, List<tower_station>> countyMapStations = new HashMap<String, List<tower_station>>();
        List<Tower_Link> selectLinks = new ArrayList<Tower_Link>();
        for (tower_station station : stationList) {
            String county = station.getCounty();
            if (countyMapStations.containsKey(county)) {
                countyMapStations.get(county).add(station);
            } else {
                ArrayList<tower_station> arrayList = new ArrayList<tower_station>();
                arrayList.add(station);
                countyMapStations.put(county, arrayList);
            }
        }
        for (String county : countyMapStations.keySet()) {
            Tower_Link selectLink = new Tower_Link();
            selectLink.setCounty(county);
            selectLink.setStations(countyMapStations.get(county));
            selectLinks.add(selectLink);
        }
        resultList.add(selectLinks);
        return resultList;
    }



    /**
     * 气象要素查询
     *
     * @param request
     * @param model
     * @return
     * @author
     * @throws ParseException
     * @date 2019年7月28日
     */
    @RequestMapping("/rainSearch")
    @ResponseBody
    public Object rainQuery(HttpServletRequest request, Model model) throws ParseException {
        Date startDate = DateTime.parseDateTime(request.getParameter("startDate")).toDate();
        Date endDate = DateTime.parseDateTime(request.getParameter("endDate")).toDate();
        String startDate1 = DateTime.parseDateTime(request.getParameter("startDate")).toDateTimeString();
        String endDate1 = DateTime.parseDateTime(request.getParameter("endDate")).toDateTimeString();
        String[] countys = request.getParameter("countys").split(",");
        String type = request.getParameter("type");
        String element = request.getParameter("element");
        String elemType = request.getParameter("text");
        String equMap = request.getParameter("equMap");
        final String etype=elemType;
        List<Object> result = new ArrayList<>();
        //根据参数生成唯一MD5编码
        String TowerrainSearchId = MD5Utils.MD5Encode(startDate.toString() + endDate.toString() + countys + type + element + elemType, "utf-8");
        if (TowerrainSearchId.equals(request.getSession().getAttribute("TowerrainSearchId"))) {
            //已经进行过缓存了,直接读取缓存内容，没有缓存则进行查询
            result = (ArrayList) request.getSession().getAttribute("TowerrainSearchData");
        } else {
        request.getSession().setAttribute("TowerelemType", elemType);
        request.getSession().setAttribute("Towerelement", element);
        request.getSession().setAttribute("TowerrainSearchId", TowerrainSearchId);
        if (elemType.equals("整点雨量")) {
            elemType = "1小时雨量";
        }
        if (elemType.equals("累积雨量")) {
            elemType = "雨量";
        }
        if (elemType.contains("温度")) {
            elemType = "温度";
        }
        if (elemType.contains("湿度")) {
            elemType = "湿度";
        }
        if (elemType.contains("风")) {
            elemType = "风速";
        }
        if (elemType.contains("气压")) {
            elemType = "气压";
        }
        ActualElemQuery elemQuery = new ActualElemQuery();
        elemQuery.setCountys(Arrays.asList(countys));
        elemQuery.setElement(element);
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        elemQuery.setType(type);
        List<ActualData> resultList = towerSatelliteService.qxElementQuery(elemQuery);
        List<ElemContourSet> contourSet = towerSatelliteService.getElemContourSet(elemType);
            String txtPath = "";
            if (!elemType.contains("能见度")) {
                //生成等值图
                if (equMap.equals("true")) {
                    Thread t = null;
                    List<ActualData> finalResultList = resultList;
                    txtPath = webRootKey(finalResultList, contourSet, etype, request);
                }
                result.add(ClassifyElemByValue(resultList, contourSet, elemType));
                result.add(contourSet);
                if (!StringUtil.IsNullOrEmpty(txtPath)) {
                    //服务器地址
//                    DmServiceConnector conn = new DmServiceConnector("localhost", "6163");//改成181地址
                    String uniqueno = conn.getCallPlugin("ContourService.InterpolationService", "GetInterpolationWork",
                            txtPath);
                    result.add(uniqueno);
                }
            } else result.add("");




            String RainDisp ="";
            double Total = 0.0;
            double noRain=0.0;
            int littleRain=0;
            int middleRain=0;
            int bigRain=0;
            int hervyRain=0;
            int hardRain=0;
            int veryHardRain=0;

            for(int i=0;i<resultList.size();i++){
                double rain=resultList.get(i).getRain();
                if (rain >= 200)
                {
                    veryHardRain++;
                }
                else if (rain >= 100)
                {
                    hardRain++;

                }
                else if (rain >= 50)
                {
                    hervyRain++;
                }
                else if (rain >= 25)
                {
                    bigRain++;
                }
                else if (rain >= 10)
                {
                    middleRain++;
                }
                else if (rain > 0)
                {
                    littleRain++;
                }
                else
                {
                    noRain++;
                }

            }
            if (veryHardRain != 0)
            {
                if (!startDate.equals(endDate)){
                    RainDisp = String.format("根据监测显示，时间:%s时至%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨,%s站大暴雨，%s站特大暴雨。其中最大降雨量为%smm(%s)",startDate1, endDate1,resultList.size(),resultList.size(),littleRain, middleRain, bigRain, hervyRain, hardRain, veryHardRain,resultList.get(0).getRain(),resultList.get(0).getStationName());

                }else {
                    RainDisp = String.format("根据监测显示，时间:%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨,%s站大暴雨，%s站特大暴雨。其中最大降雨量为%smm(%s)",startDate1,resultList.size(), littleRain, middleRain, bigRain, hervyRain, hardRain, veryHardRain,resultList.get(0).getRain(),resultList.get(0).getStationName());

                }

            }
            else if (hardRain != 0)
            {
                if (!startDate.equals(endDate)){
                    RainDisp = String.format("根据监测显示，时间:%s时至%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨,%s站大暴雨。其中最大降雨量为%smm(%s)",startDate1, endDate1,resultList.size(),littleRain, middleRain, bigRain, hervyRain, hardRain,resultList.get(0).getRain(),resultList.get(0).getStationName());

                }else {
                    RainDisp = String.format("根据监测显示，时间:%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨,%s站大暴雨。其中最大降雨量为%smm(%s)",startDate1,resultList.size(), littleRain, middleRain, bigRain, hervyRain, hardRain,resultList.get(0).getRain(),resultList.get(0).getStationName());
                }
            }
            else if (hervyRain != 0)
            {
                if (!startDate.equals(endDate)){
                    RainDisp = String.format("根据监测显示，时间:%s时至%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨。其中最大降雨量为%smm(%s)",startDate1, endDate1,resultList.size(),littleRain, middleRain, bigRain, hervyRain,resultList.get(0).getRain(),resultList.get(0).getStationName());

                }else {
                    RainDisp = String.format("根据监测显示，时间:%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨。其中最大降雨量为%smm(%s)",startDate1,resultList.size(), littleRain, middleRain, bigRain, hervyRain,resultList.get(0).getRain(),resultList.get(0).getStationName());

                }
            }
            else if (bigRain != 0)
            {
                if (!startDate.equals(endDate)){
                    RainDisp = String.format("根据监测显示，时间:%s时至%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨。其中最大降雨量为%smm(%s)",startDate1, endDate1,resultList.size(),littleRain, middleRain, bigRain, resultList.get(0).getRain(),resultList.get(0).getStationName());

                }else {
                    RainDisp = String.format("根据监测显示，时间:%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨。其中最大降雨量为%smm(%s)",startDate1,resultList.size(), littleRain, middleRain, bigRain,resultList.get(0).getRain(),resultList.get(0).getStationName());
                }
            }
            else if (middleRain != 0)
            {
                if (!startDate.equals(endDate)){
                    RainDisp = String.format("根据监测显示，时间:%s时至%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨。其中最大降雨量为%smm(%s)",startDate1, endDate1,resultList.size(),littleRain, middleRain,resultList.get(0).getRain(),resultList.get(0).getStationName());

                }else {
                    RainDisp = String.format("根据监测显示，时间:%s时,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨。其中最大降雨量为%smm(%s)",startDate1,resultList.size(), littleRain, middleRain,resultList.get(0).getRain(),resultList.get(0).getStationName());

                }
            }
            else if (littleRain != 0)
            {
                if (!startDate.equals(endDate)){
                    RainDisp = String.format("根据监测显示，时间:%s时至%s时,据全市%s个区域自动气象站资料统计，有%s站小雨。其中最大降雨量为%smm(%s)",startDate1, endDate1,resultList.size(),littleRain,resultList.get(0).getRain(),resultList.get(0).getStationName());

                }else {
                    RainDisp = String.format("根据监测显示，时间:%s时,据全市%s个区域自动气象站资料统计，有%s站小雨。其中最大降雨量为%smm(%s)",startDate1,resultList.size(), littleRain,resultList.get(0).getRain(),resultList.get(0).getStationName());

                }
            }
            else
            {
                if (!startDate.equals(endDate)) {
                    RainDisp = String.format("根据监测显示，时间:%s时至%s时,据全市%s个区域自动气象站资料统计，有%s站无雨。", startDate1, endDate1,resultList.size(),noRain);
                }else {
                    RainDisp = String.format("根据监测显示，时间:%s时,据全市%s个区域自动气象站资料统计，有%s站无雨。", startDate1,resultList.size(),noRain);
                }
            }
            result.add(RainDisp);
            request.getSession().setAttribute("TowerrainSearchData", result);
        }
        return result;
    }

    private  String webRootKey(List<ActualData> resultList, List<ElemContourSet> contourSet, String type,HttpServletRequest request) {
        List<ContoursData> contoursDataList = new ArrayList<ContoursData>();
        List<Equalline> equallineList = new ArrayList<Equalline>();
        String result = "";

        for (ActualData actualData : resultList) {
            ContoursData contoursData = new ContoursData();
            //这里使用经纬度的坐标
            contoursData.setX(actualData.getLon());
            contoursData.setY(actualData.getLat());
            if (type.indexOf("雨量") != -1) {
                contoursData.setVal(actualData.getRain());
            }
            if (type.indexOf("温度") !=-1) {
                contoursData.setVal(actualData.getTemp());
            }
            if (type.indexOf("风")!=-1) {
                contoursData.setVal(actualData.getWinds());
            }
            if (type.indexOf("湿")!=-1) {
                contoursData.setVal(actualData.getHumid());
            }
            if (type.indexOf("气压")!=-1) {
                contoursData.setVal(actualData.getPressure());
            }
            contoursDataList.add(contoursData);
        }
        for (ElemContourSet elemContourSet : contourSet) {
            Equalline equalline = new Equalline();
            equalline.setdValue(elemContourSet.getElementValue());
            equalline.setiColor(elemContourSet.getElementColor());
            equallineList.add(equalline);
        }
        try {
            String gridFile = DbConfig.TAB;
            //生成数据存入文档
            result= SetParamToFile(contoursDataList, equallineList, gridFile,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //生成数据存入txt文档
    public String SetParamToFile(List<ContoursData> data,List<Equalline> equallineList, String gridFile,HttpServletRequest request) throws IOException {
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/TTService/";
        String serviceUrl = basePath + "data.txt";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\TTService\\";
        String serviceFilePath = urlpath + "data.txt";// 服务器文件
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录

        FileWriter fw = new FileWriter(serviceFilePath);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("[基本参数]");
        bw.newLine();
        bw.write(data.size() + "," + equallineList.size() + "," + gridFile + "," + 1 + "," + 1.5 + "," + 5 + "," + 1 + "," + 0 + "," + 0 + "," + 1);
        bw.newLine();
        bw.write("[数据]");
        bw.newLine();
        for (ContoursData datum : data) {
            //经纬度转墨卡托
            MapProjPara oldmpara = new MapProjPara();
            oldmpara.setpProjType((short)1); //经纬度
            oldmpara.setpEarthParam((short)12); //2000
            MapProjPara newmpara = new MapProjPara();
            newmpara.setpProjType((short) 5); //墨卡托
            newmpara.setpEarthParam((short) 7); //WGS-84
            newmpara.setPlat(0);
            newmpara.setpLon(0);
            MapProj mercator = new MapProj(oldmpara, newmpara);
            double[] xy = mercator.Convxy(datum.getX(), datum.getY());
            if(xy.length==2) {
                DmMapPoint dt = new DmMapPoint(xy[0], xy[1]);
                bw.write(dt.x + "\t" + dt.y + "\t" + datum.getVal());
                bw.newLine();
            }
        }
        bw.write("[分级参数]");
        bw.newLine();
        for (Equalline equalline : equallineList) {
            bw.write(equalline.getdValue()+","+equalline.getiColor()+","+equalline.getiColor()+","+1+","+0+","+equalline.getiColor()+","+0+","+0+","+0+","+0);
            bw.newLine();
        }
        bw.close();
        fw.close();
        return serviceUrl;
    }


    @RequestMapping("/TowerDownWeathersmall")
    @ResponseBody
    public  void    TowerDownWeathersmall(HttpServletRequest request, HttpServletResponse response){
        String strStartDate = request.getParameter("startDate");
        String strEndDate = request.getParameter("endDate");
        String elemType = (String) request.getSession().getAttribute("TowerelemType");
        String element = (String) request.getSession().getAttribute("Towerelement");
        List<Object> list = new ArrayList<>();
        if (request.getSession().getAttribute("TowerrainSearchData")!=null) {
            //已经进行过缓存了,直接读取缓存内容，没有缓存则进行查询
            list = (ArrayList) request.getSession().getAttribute("TowerrainSearchData");
        }
        // excel标题
        String[] title = {"站点编号", "站点名称",elemType};
        String fileName ="";
        if (!strStartDate.equals(strEndDate)&&!elemType.contains("整点")){
            // excel文件名
            fileName = strStartDate+"时"+"至"+strEndDate+"时"+ elemType+"表格统计"+".xls";
        }else {
            fileName = strStartDate+"时"+ elemType+"表格统计"+".xls";
        }

        // sheet名
        String sheetName = "实况数据表";


        List<ActualData> list1 = (List<ActualData>) list.get(0);
        String[][] content = new String[list1.size()][];

        for (int i=0;i<list1.size();i++){
            content[i] = new String[title.length];
            content[i][0] = list1.get(i).getStationId();
            content[i][1] =  list1.get(i).getStationName();
            switch (element){
                case "rain":
                    content[i][2] = String.valueOf(list1.get(i).getRain()) ;
                    break;
                case "temp":
                    content[i][2] =String.valueOf( list1.get(i).getTemp());
                    break;
                case "winds":
                    content[i][2] =String.valueOf( list1.get(i).getWinds());
                    break;
                case "humid":
                    content[i][2] =String.valueOf( list1.get(i).getHumid());
                    break;
                case "pressure":
                    content[i][2] =String.valueOf( list1.get(i).getPressure());
                    break;
            }
        }


        // 创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        // 响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 自动站气象要素颜色归类
     *
     * @param actualDatas
     * @param contourSets
     * @return
     * @author dsq
     * @date 2018年7月17日
     */
    public List<ActualData> ClassifyElemByValue(List<ActualData> actualDatas, List<ElemContourSet> contourSets, String elemType) {
        for (ActualData actualData : actualDatas) {
            double value = 0d;
            int color = 16777215;// 白色，默认颜色
            switch (elemType) {
                case "雨量":
                case "1小时雨量":
                case "3小时雨量":
                case "6小时雨量":
                case "12小时雨量":
                case "24小时雨量":
                    value = actualData.getRain();
                    break;
                case "温度":
                    value = actualData.getTemp();
                    break;
                case "风速":
                    value = actualData.getWinds();
                    break;
                case "湿度":
                    value = actualData.getHumid();
                    break;
                case "气压":
                    value = actualData.getPressure();
                default:
                    break;
            }
            for (int i = 0; i < contourSets.size(); i++) {
                ElemContourSet contourSet = contourSets.get(i);
                double level = contourSet.getElementValue();
                if (value >= level) {
                    color = contourSet.getElementColor();
                }
            }
            actualData.setColor(ColorUtil.transWin32ToHtml(color));
        }
        return actualDatas;
    }

    /* 区县选择，获得（整点）雨量、温度、湿度、气压、风速 */
    @RequestMapping("/getPoint")
    @ResponseBody
    public Object getPoint(HttpServletRequest request, Model model) throws Exception {
        SmallScaleSearch selectKey = new SmallScaleSearch();// 查询类
        String startDate = request.getParameter("startDate");// 获取开始时间
        String county = request.getParameter("county");
        if(!StringUtil.IsNullOrEmpty(county)){
            String[] countys = county.split(",");
            selectKey.setCountys(Arrays.asList(countys));
        }
        selectKey.setStartDate(startDate);// 保存在selectKey中
        List<MediumSmallScale> resultList = towerSatelliteService.getPoint(selectKey);
        for (MediumSmallScale msgMediumSmallScale : resultList) {
            DmMapPoint dmDot = new DmMapPoint(msgMediumSmallScale.getLongitude(), msgMediumSmallScale.getLatitude());
            DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
            msgMediumSmallScale.setX(ltDot.x);
            msgMediumSmallScale.setY(ltDot.y);
        }
        return resultList;
    }



    @RequestMapping("/initDzWarning")
    @ResponseBody
    public Object initDZQueryPage() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(towerSatelliteService.getDZNewDate());
        result.add(endDate.AddDays(-7).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }


    @RequestMapping("/initshDzWarning")
    @ResponseBody
    public Object initShQueryPage() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(towerSatelliteService.getshNewDate());
        result.add(endDate.AddDays(-7).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }



    @RequestMapping("/initnlWarning")
    @ResponseBody
    public Object initnlWarning() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(towerSatelliteService.getnlNewDate());
        result.add(endDate.AddDays(-7).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }


    @RequestMapping("/initqsQueryPage")
    @ResponseBody
    public Object initqsQueryPage() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(towerSatelliteService.getqsNewDate());
        result.add(endDate.AddDays(-7).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }




    @RequestMapping("/showDzWarning")
    @ResponseBody
    public Object showDzWarning(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return towerSatelliteService.getTouristProduct(-1, "铁塔地质灾害预报", startDate, endDate);// 查询地质灾害
    }

    @RequestMapping("/shDzWarning")
    @ResponseBody
    public Object shDzWarning(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return towerSatelliteService.getTouristProduct(-1, "铁塔山洪灾害预报", startDate, endDate);// 查询地质灾害
    }


    @RequestMapping("/nlWarning")
    @ResponseBody
    public Object nlWarning(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return towerSatelliteService.getTouristProduct(-1, "铁塔城市内涝预报", startDate, endDate);// 查询地质灾害
    }





    @RequestMapping("/showDzpart")
    @ResponseBody
    public Object showDzpart(HttpServletRequest request, Model model) {
        String bindid = request.getParameter("bindid");
        List<DZWarning> result = new ArrayList<DZWarning>();
        if (!bindid.equals("")) {
            result = towerSatelliteService.getDzpart(bindid);// 查询地质灾害预警区
        }
        for (DZWarning dzWarning : result) {
            if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
                dzWarning.setEntites(cEntities);
            }
            Date date = dzWarning.getDateChar();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDateChar(null);
        }
        return result;
    }




    @RequestMapping("/showshpart")
    @ResponseBody
    public Object showshpart(HttpServletRequest request, Model model) {
        String bindid = request.getParameter("bindid");
        List<sl_warning> result = new ArrayList<sl_warning>();
        if (!bindid.equals("")) {
            result = towerSatelliteService.getshpart(bindid);// 查询地质灾害预警区
        }
        for (sl_warning dzWarning : result) {
            if (dzWarning.getGradearea2() != null && !dzWarning.getGradearea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradearea3() != null && !dzWarning.getGradearea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradearea4() != null && !dzWarning.getGradearea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradearea5() != null && !dzWarning.getGradearea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
                dzWarning.setCentity(cEntities);
            }
            Date date = dzWarning.getDatechar();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDatechar(null);
        }
        return result;
    }


    @RequestMapping("/shownlpart")
    @ResponseBody
    public Object shownlpart(HttpServletRequest request, Model model) {
        String bindid = request.getParameter("bindid");
        List<waterlogging_fcst> result = new ArrayList<waterlogging_fcst>();
        if (!bindid.equals("")) {
            result = towerSatelliteService.getnlpart(bindid);// 查询地质灾害预警区
        }
        for (waterlogging_fcst dzWarning : result) {
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
                dzWarning.setEntites(cEntities);
            }
            Date date = dzWarning.getMaketime();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDateChar(null);
        }
        return result;
    }


    @RequestMapping("/showTxt")
    @ResponseBody
    public String showTxt(HttpServletRequest request, Model model) {
        // 处理txt文件
        String result = "";
        String txtId = request.getParameter("txtId");// 文档编号
        String fileName = request.getParameter("txtName");// 文档名称
        String tableName = request.getParameter("tableName");
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\warning\\";
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);
        String txtType = fileName.split("\\.")[fileName.split("\\.").length - 1];
        // 判断文件类型是否是word
        if (txtType.equals("txt")) {
            String txtPath = urlpath + fileName;
            File txtFile = new File(txtPath);
            if (txtFile.exists()) {
                result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
            } else {
                // 从mongdo中获取文件
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", txtId);
                map.put("table_name", tableName);
                map.put("collectionName", "txt_file");
                byte[] data = ms.selectData(map);
                if (data == null) {
                    return "";
                }
                // 下载doc文件
                FileUtil.bytesToFile(data, txtPath);
                result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
            }
        }
        return result;
    }

    @RequestMapping("/showDoc")
    @ResponseBody
    public String showDoc(HttpServletRequest request, Model model) {
        String servicePath = "";
        String docId = request.getParameter("docId");// 文档编号
        String fileName = request.getParameter("docName");// 文档名称
        String tableName = request.getParameter("tableName");
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\warning\\";
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path;
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);
        String docType = fileName.split("\\.")[fileName.split("\\.").length - 1];
        // 判断文件类型是否是word
        if (docType.contains("doc")) {
            String localPath = urlpath + fileName;
            String pdfPath = urlpath + fileName.replace(docType, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                servicePath = "\\Temp\\warning\\" + fileName.replace(docType, "pdf");
                servicePath = basePath+servicePath;
            } else {
                // 从mongdo中获取文件
                Map<String, Object> map = new HashMap<String, Object>();
                // map.put("dateyear", String.valueOf(doppler.getDataYear()));
                map.put("id", docId);
                map.put("table_name", tableName);
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                // 本地文件
                try {
                    servicePath = "\\Temp\\warning\\" + fileName.replace(docType, "pdf");
                    servicePath = basePath+servicePath;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }

        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }


    @RequestMapping("/showDZpoint")
    @ResponseBody
    public Object showDZpoint(HttpServletRequest request, Model model) {
        String result = "[";
        List<tour_stations> tourStations = towerSatelliteService.getTourStation();
        String poss = request.getParameter("pos");// 坐标
        String[] posArr = poss.split("\\*");// 三个部分，*分隔
        List<String> dpoint = new ArrayList<String>();
        String stanames = "";
        for (String pos : posArr) {
            try {
                if (pos == null || pos.equals("")) {
                    continue;
                }
                String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                DmMapPoint[] points = new DmMapPoint[dotset.length];
                Integer index = 0;
                for (String strDot : dotset) {
                    String[] dot = strDot.split(" ");
                    DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    points[index] = dmDot;
                    index++;
                }
                for (tour_stations tour : tourStations) {
                    DmMapPoint dmDotJW = new DmMapPoint(tour.getLongitude(), tour.getLatitude());
                    DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    MapCommon dmMapCom = new MapCommon();
                    if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotLb.x,dmDotLb.y)){
                        if (!tour.getDisasterids().equals("")) {
                            String[] point = tour.getDisasterids().split(";");
                            for (int i = 0; i < point.length; i++) {
                                if (!dpoint.contains(point[i])) {
                                    dpoint.add(point[i]);
                                }
                            }
                        }
                        if (!stanames.contains(tour.getStationname())) {
                            stanames += tour.getStationname();
                            result += "{";
                            result += "\"tourname\":\"" + tour.getStationname() + "\",";
                            result += "\"grade\":\"" + tour.getGrade() + "\",";
                            result += "\"people\":\"" + tour.getPeople() + "\",";
                            result += "\"phone\":\"" + tour.getPeople() + "\",";
                            result += "\"disasterscale\":\"" + "" + "\",";
                            result += "\"intime\":\"" + "" + "\",";
                            result += "\"firsttime\":\"" + "" + "\",";
                            result += "\"disType\":\"" + "" + "\",";
                            result += "\"disName\":\"" + tour.getStationname() + "\",";
                            result += "\"threatproperty\":\"" + "" + "\",";
                            result += "\"threathouseholds\":\"" + "" + "\",";
                            result += "\"nextdefendmeasures\":\"" + "" + "\",";
                            result += "\"monitorperson\":\"" + "" + "\",";
                            result += "\"tel\":\"" + "" + "\",";
                            result += "\"monitorprincipal\":\"" + "" + "\",";
                            result += "\"monitorprincipaltel\":\"" + "" + "\",";
                            result += "\"motiondir\":\"" + "" + "\",";
                            result += "\"lon\":" + tour.getLongitude() + ",";
                            result += "\"lat\":" + tour.getLatitude() + "";
                            result += "},";
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
        }
        List<potential_points> resultList = new ArrayList<potential_points>();
        if (dpoint != null && dpoint.size() > 0) {
            resultList = towerSatelliteService.getDisPoint(dpoint);
        }
        for (potential_points city : resultList) {
            Double lon = Double.parseDouble(city.getLon());
            Double lat = Double.parseDouble(city.getLat());
            result += "{";
            result += "\"tourname\":\"" + "" + "\",";
            result += "\"grade\":\"" + "" + "\",";
            result += "\"people\":\"" + "" + "\",";
            result += "\"phone\":\"" + "" + "\",";
            result += "\"disasterscale\":\"" + city.getDis_scale() + "\",";
            result += "\"disType\":\"" + city.getDis_type() + "\",";
            result += "\"disName\":\"" + city.getPp_name() + "\",";
            result += "\"threatproperty\":\"" + city.getThreat_pop() + "\",";
            result += "\"threathouseholds\":\"" + city.getThreat_prop() + "\",";
            result += "\"monitorperson\":\"" + city.getContact() + "\",";
            result += "\"tel\":\"" + city.getContact_tel() + "\",";
            result += "\"monitorprincipal\":\"" + city.getContact1() + "\",";
            result += "\"monitorprincipaltel\":\"" + city.getContact1_tel() + "\",";
            result += "\"lon\":" + lon + ",";
            result += "\"lat\":" + lat + "";
            result += "},";
        }
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        result = result + "]";
        return result;
    }
    /**
     * 生成等值图
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getImageUrl")
    @ResponseBody
    public Object getImageUrl(HttpServletRequest request, Model model) {
        List<Object> result = new ArrayList<>();
        String uniqueno = request.getParameter("uniqueno");
        String x1 = request.getParameter("x1");
        String y1 = request.getParameter("y1");
        String x2 = request.getParameter("x2");
        String y2 = request.getParameter("y2");
        String width = request.getParameter("width");
        String height = request.getParameter("height");
        String imgurl = conn.getCallPlugin("ContourService.InterpolationService", "GetContourPic",uniqueno+"|"+DbConfig.TAB+"|"+width+"|"+height+"|"+x1+","+y1+","+x2+","+y2+"|1");
        result.add(DbConfig.IMAGEURL+imgurl);
        return result;
    }

}
